<script setup>
import moment from "moment";
import { nextTick, ref, watch } from "vue";
import { getMusicDetailList, getMusicUrl } from "../../apis/user";
import emitter from "../../utils/eventBus";
import { Local } from "../../utils/storage";
import { RmMessage } from "../../utils/RmMessage";
import { storeToRefs } from "pinia";
import { musicStore } from "@/store/music";
import { userStore } from "@/store/user";
import { createWindow, ipcRendererSend } from "../../utils/ipcRenderer";
import { useRouter, useRoute } from "vue-router";
import { getMusicLike } from "../../apis/music";
const { songId, songListIds, playOrder, likeIdList,soundQuality } = storeToRefs(
  musicStore()
);
const { loginStatus } = storeToRefs(userStore());

const router = useRouter();
const route = useRoute();

const musicUrl = ref("");
const musicInfo = ref();
if (Local.get("musicInfo")) {
  musicInfo.value = Local.get("musicInfo");
}
if (Local.get("musicUrl")) {
  musicUrl.value = Local.get("musicUrl");
}

//当前音乐进度
const currentTime = ref();
const audio = ref();
const nowVolume = ref(50);
const isPlaying = ref(false);
const sliderTime = ref();
const isChange = ref(false);
const maxTime = ref();
const isShow = ref(false);

const openPlay = () => {
  isShow.value = true;
};

if (Local.get("maxTime")) {
  maxTime.value = Local.get("maxTime");
}
nextTick(() => {
  if (Local.get("currentTime")) {
    audio.value.currentTime = Local.get("currentTime");
    currentTime.value = Local.get("currentTime");
  }
  if (Local.get("volume")) {
    nowVolume.value = Local.get("volume");
  } else {
    nowVolume.value = 50;
  }
  audio.value.volume = nowVolume.value / 100;
});

emitter.off("playMusic");
emitter.on("playMusic", (data) => {
  songId.value = data;
  // //获取歌曲链接
  // getMusicUrls(data);
  // //获取播放歌曲信息
  // musicInfo.value = Local.get("musicInfo");
  // maxTime.value = parseInt(moment(musicInfo.value.dt).format("X"));
  // Local.set("maxTime", maxTime.value);
});

//监听详情页的上一首
emitter.on("beforeMusic", () => {
  preSong();
});
//监听详情页的下一首
emitter.on("nextMusic", () => {
  nextSong();
});
//监听详情页的播放
emitter.on("playSong", () => {
  playSong();
});
//监听详情页的暂停
emitter.on("pauseSong", () => {
  pauseSong();
});
//监听详情页的拖拽滑动
emitter.on("sliderStep", (data) => {
  handleTime(data);
});
//播放视频时暂停歌曲播放
emitter.on("playVideo", () => {
  audio.value.pause();
  isPlaying.value = false;
});

const isLike = ref(likeIdList.value.indexOf(songId.value) != -1);

watch(
  () => songId.value,
  (val) => {
    songId.value = val;
    isLike.value = likeIdList.value.indexOf(songId.value) != -1;
    getMusicDetailList({ ids: val }).then((res) => {
      musicInfo.value = res.songs[0];
      Local.set("musicInfo", res.songs[0]);
      Local.set("maxTime", parseInt(moment(res.songs[0].dt).format("X")));
      maxTime.value = parseInt(moment(res.songs[0].dt).format("X"));
      getMusicUrls(val);
      ipcRendererSend("windows-param", {
        emit: "updateSongId",
        data: val,
        targetName: "songListDetail",
      });
    });
  }
);

//获取歌曲链接方法
const getMusicUrls = (id) => {
  let ids = Local.get("songList").map((item) => item.id);
  songId.value = id;
  getMusicUrl({ id: id, level: soundQuality.value }).then((res) => {
    musicUrl.value = res.data[0].url;
    Local.set("musicUrl", musicUrl.value);
    //判断能否播放
    nextTick(() => {
      if (musicUrl.value) {
        playSong();
      } else if (
        ids.indexOf(songId.value) == ids.length - 1 &&
        !musicUrl.value
      ) {
        pauseSong();
      } else {
        RmMessage.warning("歌曲暂无版权,为您播放下一首");
        setTimeout(() => {
          nextSong();
        }, 1500);
      }
    });
  });
};
//点击播放
const playSong = () => {
  audio.value.play();
  isPlaying.value = true;
};
const playLoad = () => {
  audio.value.load();
  isPlaying.value = true;
};
//点击暂停
const pauseSong = () => {
  audio.value.pause();
  isPlaying.value = false;
};
//改变音量
const changeVolume = () => {
  audio.value.volume = nowVolume.value / 100;
  Local.set("volume", nowVolume.value);
};
//改变播放模式
const changeOrder = () => {
  if (playOrder.value == 2) {
    playOrder.value = 0;
  } else {
    playOrder.value++;
  }
};
//滑动改变歌曲进度
const handleTime = (data) => {
  if (maxTime.value === 0) return;
  audio.value.currentTime = data;
  isChange.value = false;
};
//监听歌曲变化
const durationUpdate = (data) => {
  Local.set("currentTime", audio.value.currentTime);
  if (isChange.value === true) return;
  //滑块滑动
  sliderTime.value = audio.value.currentTime;
  // currentTime.value = moment(audio.value.currentTime * 1000).format("mm:ss");
  currentTime.value = audio.value.currentTime;
  //保存当前歌曲原始秒数
  let time = audio.value.currentTime;
};
//下一首
const nextSong = () => {
  let ids = Local.get("songList").map((item) => item.id);
  let index = ids.indexOf(songId.value);
  //判断播放模式
  switch (playOrder.value) {
    case 0:
      cirPlay(index, ids);
      break;
    case 1:
      rePlaySong();
      break;
    case 2:
      randomPlay(index, ids);
      break;
  }
};

//上一首
const preSong = () => {
  // let songId = songId.value;
  let ids = Local.get("songList").map((item) => item.id);
  let index = ids.indexOf(songId.value);
  //判断播放模式
  switch (playOrder.value) {
    case 0:
      //保存当前歌曲id
      if (index == 0) {
        index = ids.length;
      }
      songId.value = ids[index - 1];
      break;
    case 1:
      rePlaySong();
      break;
    case 2:
      randomPlay(index, ids);
      break;
  }
};

//列表循环
const cirPlay = (index, idList) => {
  //保存当前歌曲id
  if (index == idList.length - 1) {
    index = -1;
  }
  songId.value = idList[index + 1];
};
//单曲循环
const rePlaySong = () => {
  audio.value.load();
  audio.value.play();
};
//随机播放
const randomPlay = (index, idList) => {
  let randomNum = Math.round(Math.random() * idList.length);
  songId.value = idList[randomNum];
};

const onPause = () => {};
const songPlay = () => {};

//打开播放列表
const handleList = () => {
  if (route.path == "/willList") {
    router.go(-1);
  } else {
    router.push("/willList");
  }
};

emitter.on("offPlay", () => {
  isShow.value = false;
});

const keyDown = () => {
  //监听键盘按钮
  document.onkeyup = function (event) {
    window.event.preventDefault();
    if (event.code == "Space") {
      if (isPlaying.value) {
        pauseSong();
      } else {
        playSong();
      }
    } else if (event.key == "ArrowRight") {
      nextSong();
    } else if (event.key == "ArrowLeft") {
      preSong();
    }
  };
};

keyDown();

const handleLike = async (type, id) => {
  let res = await getMusicLike(id, type);
  if (!res.code) {
    return RmMessage.success("请勿重复添加哦!");
  }
  // console.log(data);
  if (res.code == 200 && type == true) {
    RmMessage.success("已添加到我喜欢的音乐");
    isLike.value = true;
    emitter.emit("updateUser");
  } else {
    RmMessage.success("取消喜欢成功");
    isLike.value = false;
    emitter.emit("updateUser");
  }
};
</script>

<template>
  <div class="foot-container f-a-c">
    <div class="music_slider">
      <el-slider
        :show-tooltip="false"
        @mousedown.native="isChange = true"
        @mouseup.native="isChange = false"
        :max="maxTime"
        @change="handleTime"
        v-model="sliderTime"
      ></el-slider>
    </div>
    <div v-if="musicInfo" class="music_info f-a-c">
      <div class="cover" v-if="musicInfo.al">
        <el-image :src="musicInfo.al.picUrl + `${'?param=100y100'}`"></el-image>
        <div @click="openPlay" class="silder-top">
          <img src="../../assets/images/music/topslider.png" alt="" />
        </div>
      </div>
      <img v-else src="../../assets/images/logo/logo2.png" />
      <div class="info">
        <div class="music_name">{{ musicInfo.name }}</div>
        <div class="artist_name">{{ musicInfo.ar[0].name }}</div>
      </div>
      <div v-if="loginStatus">
        <i
          v-if="!isLike"
          @click="handleLike(true, songId)"
          class="iconfont icon-aixin1"
        ></i>
        <i
          v-else
          @click="handleLike(false, songId)"
          class="iconfont icon-aixin"
        ></i>
      </div>
    </div>
    <div class="btn_wrap">
      <div class="play_btn">
        <i @click="preSong" class="iconfont icon-shangyishou"></i>
        <i
          v-if="isPlaying"
          @click="pauseSong"
          class="iconfont icon-pause-full"
        ></i>
        <i v-else @click="playSong" class="iconfont icon-bofang"></i>
        <i @click="nextSong" class="iconfont icon-xiayishou"></i>
      </div>
    </div>
    <div class="volune_wrap">
      <i
        @click="handleList()"
        class="iconfont icon-yinleliebiao"
        :class="{ active: route.path == '/willList' }"
      ></i>
      <div @click="changeOrder" class="play_order">
        <el-tooltip content="列表循环" effect="light">
          <i
            v-show="playOrder == 0"
            class="iconfont icon-bofang-xunhuanbofang"
          ></i>
        </el-tooltip>
        <el-tooltip content="单曲循环" effect="light">
          <i v-show="playOrder == 1" class="iconfont icon-danquxunhuan"></i>
        </el-tooltip>
        <el-tooltip content="随机播放" effect="light">
          <i v-show="playOrder == 2" class="iconfont icon-suijibofang"></i>
        </el-tooltip>
      </div>

      <i v-if="nowVolume != 0" class="iconfont icon-24gf-volumeMiddle"></i>
      <i v-else class="iconfont icon-24gf-volumeCross"></i>
      <div class="block">
        <el-slider
          @change="changeVolume"
          v-model="nowVolume"
          :max="100"
          :step="1"
        ></el-slider>
      </div>
    </div>
    <audio
      @timeupdate="durationUpdate"
      @ended="nextSong"
      @pause="onPause"
      @play="songPlay"
      ref="audio"
      :src="musicUrl"
    ></audio>
  </div>
  <transition name="el-zoom-in-bottom">
    <div v-show="isShow" class="music-detail">
      <msuic-detail
        :isPlaying="isPlaying"
        :currentTime="currentTime"
        :maxTime="maxTime"
        :musicDetail="musicInfo"
      ></msuic-detail>
    </div>
  </transition>
</template>

<style scoped lang="scss">
.foot-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: hsla(0, 0%, 100%, 0.86);
  backdrop-filter: saturate(180%) blur(30px);
  .music_slider {
    width: 100%;
    position: absolute;
    top: -10px;
    left: 0;
    :deep(.el-slider) {
      width: 100%;
      height: 20px;
      line-height: 20px;
      overflow: hidden;
      &:hover .el-tooltip {
        width: 11px;
        height: 11px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12),
          0 0 6px rgba(19, 18, 18, 0.54);
      }
      .el-slider__bar {
        height: 2px;
      }
      .el-slider__runway {
        margin: 0;
        background-color: #e0eaf3;
        height: 2px;
        border-radius: 0;
      }
      .el-tooltip {
        margin-top: 11px;
        height: 0px;
        width: 0px;
        border: none;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
      }
      .el-slider__button-wrapper {
        width: 1px;
        height: 1px;
        .el-slider__button {
          //   border: 1px solid #000000;
          //   background-color: #000000;
          margin-top: 10px;
          width: 8px;
          height: 8px;
        }
      }
    }
  }
  .music_info {
    cursor: pointer;
    padding-left: 10px;
    .info {
      margin-left: 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      font-size: 11px;
      color: #666;
      .music_name {
        max-width: 250px;
        color: #333;
        font-size: 14px;
        font-weight: 600;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .icon-aixin1,
    .icon-aixin {
      padding: 5px;
      border-radius: 5px;
    }
    .icon-aixin1:hover {
      background-color: rgba(241, 239, 239, 0.877);
    }
    .icon-aixin:hover {
      background-color: rgba(241, 239, 239, 0.877);
    }
    .cover {
      position: relative;
      &:hover .silder-top {
        display: block;
      }
      .silder-top {
        width: 40px;
        height: 40px;
        top: 0;
        display: none;
        position: absolute;
        z-index: 333;
        background-color: rgba(238, 238, 238, 0.358);
        cursor: pointer;
        border-radius: 5px;
        border: 1px solid #ddd;
        transition: all 0.3s;
        img {
          width: 40px;
          height: 40px;
        }
      }
    }
    .el-image {
      width: 40px;
      height: 40px;
      border: 1px solid #ddd;
      border-radius: 5px;
      cursor: pointer;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 5px;
    }
    i {
      margin-left: 20px;
      font-size: 16px;
    }
  }
  .btn_wrap {
    position: absolute;
    left: 50%;
    margin-left: -60px;
    .play_btn {
      i {
        font-size: 25px;
      }
      i:hover {
        color: #ddd;
      }
      .icon-bofang,
      .icon-pause-full {
        margin: 0 20px;
      }
    }
  }
  .volune_wrap {
    position: absolute;
    right: 0;
    width: 260px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding-right: 20px;
    i {
      display: flex;
      justify-content: center;
      width: 25px;
      color: #000000;
      font-size: 16px;
      font-weight: 600;
    }
    i:hover {
      background-color: rgba(241, 241, 241, 0.555);
      border-radius: 5px;
      color: rgb(71, 29, 221);
    }
    .active {
      color: rgb(55, 70, 211);
    }
    // padding: 0 40px;
    .block {
      :deep(.el-slider) {
        width: 100px;
        .el-slider__runway {
          margin: 0;
          background-color: #e0eaf3;
          height: 4px;
          border-radius: 0;
        }
        .el-slider__bar {
          height: 4px;
          background-color: #000000;
        }
        .el-slider__button-wrapper {
          width: 1px;
          height: 1px;
          .el-slider__button {
            border: 1px solid #000000;
            background-color: #000000;
            margin-top: 12px;
            width: 8px;
            height: 8px;
          }
        }
        .el-tooltip {
          margin-top: 13px;
          height: 5px;
          width: 5px;
          border: #000000 2px solid;
          background-color: #000000;
          border-radius: 50%;
        }
      }
    }
  }
}
// .el-zoom-in-bottom-enter-active {
//   transition: all 0.3s ease;
// }
// .el-zoom-in-bottom-leave-active {
//   transition: all 0.3s ease;
// }
.el-zoom-in-bottom-enter-active {
  transition: all 0.2s ease;
}

.el-zoom-in-bottom-leave-active {
  transition: all 0.2s ease-out;
}

.el-zoom-in-bottom-enter-from,
.el-zoom-in-bottom-leave-to {
  transform: translateY(100vh);
}
.music-detail {
  position: fixed;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: #364640;
  z-index: 999;
  left: 0;
}
</style>
